package com.societyGames.flashForms
{
	import com.societyGames.system.EventObject;
	
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;

	public class TreeViewNode extends Sprite implements IChangeSize
	{
		private var _child:Sprite;
		private var _treeViewContainer:TreeViewContainer = new TreeViewContainer();
		private var _sizeChangedEventObject:EventObject;
		
		public function TreeViewNode(tabSize:Number)
		{
			this._sizeChangedEventObject = new EventObject(this, "SIZED_CHANGED"); 
			this._treeViewContainer.x = tabSize;
			this._treeViewContainer.y = 0;
			this._treeViewContainer.sizeChangedEventObject.addEventListener(treeViewContainerSizeChangedHandler);
			this.addChild(this._treeViewContainer);
		}
		
		public function get child():Sprite
		{
			return this._child;
		}
		
		public function set child(value:Sprite):void
		{
			if (this._child != value)
			{
				if (this._child != null)
				{
					this._child.removeEventListener(MouseEvent.CLICK, clickHandler);
					this.removeChild(this._child);
					this._treeViewContainer.y = 0;
				}				
				this._child = value;
				if (this._child != null)
				{
					this._child.addEventListener(MouseEvent.CLICK, clickHandler);
					this.addChild(this._child);
					this._treeViewContainer.y = this._child.height;
					this._child.buttonMode = true;
					treeViewContainerSizeChangedHandler(null);
				}
				this._sizeChangedEventObject.dispatchEvent();
			}
		}
		
		//IChangeSize-->
		public function get sizeChangedEventObject():EventObject
		{
			return this._sizeChangedEventObject;
		}
		//<--IChangeSize
		
		public function get treeViewContainer():TreeViewContainer
		{
			return this._treeViewContainer;
		}
		
		private function clickHandler(event:MouseEvent):void
		{
			this._treeViewContainer.isExpanded = !this._treeViewContainer.isExpanded;
		}
		
		private function treeViewContainerSizeChangedHandler(event:Event):void
		{
			if (this._child != null)
			{
				if (treeViewContainer.nodeCount == 0)
				{
					this._child.useHandCursor = false;
				}
				else
				{
					this._child.useHandCursor = true;
				}
			}
			this._sizeChangedEventObject.dispatchEvent();
		}
	}
}